package fr.kotton.myorganizer.task.fragment;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;

import fr.kotton.myorganizer.R;
import fr.kotton.myorganizer.bean.Task;
import fr.kotton.myorganizer.db.MyOrganizerDbContract.TaskEntry;
import fr.kotton.myorganizer.task.interfaces.TasksQueryCompleteListener;
import fr.kotton.myorganizer.utils.Consts;
import fr.kotton.myorganizer.utils.sql.BeanToDbConverter;
import fr.kotton.myorganizer.utils.sql.DatabaseReader;
import fr.kotton.myorganizer.utils.sql.DatabaseUpdater;
import fr.kotton.myorganizer.utils.sql.DbToBeanConverter;
import fr.kotton.myorganizer.utils.sql.SqlRawQuery;
import fr.kotton.myorganizer.utils.sql.SqlUpdateQuery;

public class EditTaskFragment extends DialogFragment {

    private Task mTask;

    private Context mContext;

    private Date mNewEndDate;
    private Date mNewEndTime;
    private TextView mTimeTextView;
    private TextView mDateTextView;

    public EditTaskFragment() {
    }

    private static String datePickerStringPadding(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity();

        View rootView = inflater.inflate(R.layout.fragment_edit_task, container, false);

        mTimeTextView = (TextView) rootView.findViewById(R.id.fragment_edit_task_task_end_time);

        ImageView lTimePickerImageView = (ImageView) rootView.findViewById(R.id.fragment_edit_task_time_picker);
        lTimePickerImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomTimePicker();
            }
        });

        mDateTextView = (TextView) rootView.findViewById(R.id.fragment_edit_task_task_end_date);

        ImageView lDatePickerImageView = (ImageView) rootView.findViewById(R.id.fragment_edit_task_date_picker);
        lDatePickerImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDatePicker();
            }
        });

        setHasOptionsMenu(true);

        Bundle lArgs = this.getArguments();
        Integer lTaskId = lArgs.getInt(Consts.INTENT_REF_TASK_ID, 0);

        // Configuration des callbacks appelés lorsqu'une requête DB est terminée
        TasksQueryCompleteListener lTasksDbQueryCompletedListener = new TasksQueryCompleteListener() {

            @Override
            public void onTasksReadQueryComplete(Cursor pCursor) {
                parseTasksReadQueryResult(pCursor);
            }

            @Override
            public void onTasksDeleteQueryComplete() {
            }
        };

        // Requête pour récupérer la tâches sélectionnée
        SqlRawQuery lSqlRawQuery = new SqlRawQuery();
        lSqlRawQuery.setQuery("SELECT task.task_id, Title, endDate, task_to_task_group.task_id as task_id_ref, task_to_task_group.taskgroup_id, task_group.name, task_group.color FROM task LEFT JOIN task_to_task_group ON task_id_ref = task.task_id LEFT JOIN task_group ON task_to_task_group.taskgroup_id = task_group.taskgroup_id WHERE task.task_id = " + lTaskId);
        DatabaseReader lDatabaseReader = new DatabaseReader(getActivity(), lTasksDbQueryCompletedListener);
        lDatabaseReader.execute(lSqlRawQuery);

        return rootView;
    }

    public void showCustomTimePicker() {

        final TimePicker lTimePicker = (TimePicker) ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_time_picker, null);
        //Set an initial date for the picker
        Calendar lCalendar = Calendar.getInstance();
        if (mNewEndTime != null) {
            lCalendar.setTime(mNewEndTime);
        } else {
            Date lTaskEndDate = mTask.getEndDate();
            lCalendar.setTime(lTaskEndDate);
        }

        //Set the date now
        lTimePicker.setCurrentHour(lCalendar.get(Calendar.HOUR));
        lTimePicker.setCurrentMinute(lCalendar.get(Calendar.MINUTE));
        lTimePicker.setIs24HourView(true);

        //create the dialog
        AlertDialog.Builder lAlertDialogBuilder = new AlertDialog.Builder(mContext);
        //set the title
        lAlertDialogBuilder.setTitle(getString(R.string.edit_task_end_time_picker))
                //set our date picker
                .setView(lTimePicker)
                        //set the buttons
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mNewEndTime = (new GregorianCalendar(0, 0, 0, lTimePicker.getCurrentHour(), lTimePicker.getCurrentMinute(), 0)).getTime();
                        mTimeTextView.setText(new StringBuilder().append(datePickerStringPadding(lTimePicker.getCurrentHour())).append(":").append(datePickerStringPadding(lTimePicker.getCurrentMinute())));
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                        //create the dialog and show it.
                .create().show();
    }

    public void showCustomDatePicker() {

        final DatePicker lDatePicker = (DatePicker) ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_date_picker, null);
        //Set an initial date for the picker
        Calendar lCalendar = Calendar.getInstance();
        if (mNewEndDate != null) {
            lCalendar.setTime(mNewEndDate);
        } else {
            Date lTaskEndDate = mTask.getEndDate();
            lCalendar.setTime(lTaskEndDate);
        }

        //Set the date now
        lDatePicker.updateDate(lCalendar.get(Calendar.YEAR), lCalendar.get(Calendar.MONTH), lCalendar.get(Calendar.DAY_OF_MONTH));

        //create the dialog
        AlertDialog.Builder lAlertDialogBuilder = new AlertDialog.Builder(mContext);
        //set the title
        lAlertDialogBuilder.setTitle(getString(R.string.edit_task_end_date_picker))
                //set our date picker
                .setView(lDatePicker)
                        //set the buttons
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        mNewEndDate = new Date(lDatePicker.getCalendarView().getDate());

                        DateFormat mDateFormatter = new SimpleDateFormat("EE dd MMM yyyy");
                        mDateTextView.setText(mDateFormatter.format(mNewEndDate));
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                        //create the dialog and show it.
                .create().show();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.fragment_edit_task_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.action_save_task) {

            if (taskIsModified(mTask)) {
                SqlUpdateQuery lSqlUpdateQuery = new SqlUpdateQuery();
                lSqlUpdateQuery.setTable(TaskEntry.TABLE_NAME);

                ContentValues lTaskValues = newTaskValues();

                lSqlUpdateQuery.setValues(lTaskValues);
                lSqlUpdateQuery.setWhereClause(TaskEntry.COLUMN_NAME_TASK_ID + " = ?");

                String[] lTaskId = {Integer.toString(mTask.getId())};
                lSqlUpdateQuery.setWhereArgs(lTaskId);

                DatabaseUpdater lDatabaseUpdater = new DatabaseUpdater(getActivity(), null);
                lDatabaseUpdater.execute(lSqlUpdateQuery);

                Toast.makeText(getActivity(), getText(R.string.edit_task_task_modified), Toast.LENGTH_SHORT).show();
                getActivity().finish();

            } else {
                Toast.makeText(getActivity(), getText(R.string.edit_task_task_not_modified), Toast.LENGTH_SHORT).show();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public void parseTasksReadQueryResult(Cursor pCursor) {
        if (pCursor != null) {
            LinkedList<Task> lTasksList = DbToBeanConverter.DbToTasks(pCursor);
            mTask = lTasksList.get(0);

            EditText lTaskTitle = (EditText) getView().findViewById(R.id.fragment_edit_task_task_title);
            TextView lTaskEndDate = (TextView) getView().findViewById(R.id.fragment_edit_task_task_end_date);
            TextView lTaskTime = (TextView) getView().findViewById(R.id.fragment_edit_task_task_end_time);

            lTaskTitle.setText(mTask.getTitle());
            lTaskEndDate.setText(mTask.getFormattedEndDate());
            lTaskTime.setText(mTask.getFormattedEndTime());
        }
    }

    public Boolean taskIsModified(Task pTask) {

        String lTitle = ((EditText) getView().findViewById(R.id.fragment_edit_task_task_title)).getText().toString();
        String lEndDate = ((TextView) getView().findViewById(R.id.fragment_edit_task_task_end_date)).getText().toString();
        String lEndTime = ((TextView) getView().findViewById(R.id.fragment_edit_task_task_end_time)).getText().toString();

        if (!lTitle.equals(pTask.getTitle())) {
            return true;
        }

        if (!lEndDate.equals(pTask.getFormattedEndDate())) {
            return true;
        }

        if (!lEndTime.equals(pTask.getFormattedEndTime())) {
            return true;
        }

        return false;
    }

    public ContentValues newTaskValues() {

        String lTitle = ((EditText) getView().findViewById(R.id.fragment_edit_task_task_title)).getText().toString();
        String lEndDate = ((TextView) getView().findViewById(R.id.fragment_edit_task_task_end_date)).getText().toString();
        String lEndTime = ((TextView) getView().findViewById(R.id.fragment_edit_task_task_end_time)).getText().toString();

        ContentValues lNewTaskValues = new ContentValues();

        lNewTaskValues.put(TaskEntry.COLUMN_NAME_TASK_TITLE, lTitle);
        lNewTaskValues.put(TaskEntry.COLUMN_NAME_TASK_ENDDATE, BeanToDbConverter.DateToDb(lEndDate, lEndTime));

        return lNewTaskValues;
    }
}

